package com.ruoyi.app.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import com.ruoyi.app.domain.user.Register;
import com.ruoyi.app.service.AppUserService;
import com.ruoyi.common.config.PasswordConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.utils.AESUtils;
import com.ruoyi.system.utils.ComLbsUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;

/**
 * 描述 APP登录接口
 * 作者 ZhangPing
 * 创建时间 2023/9/27 11:14
 */
@Slf4j
@RestController
@RequestMapping("/app/user")
public class AppUserController extends BaseController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private PasswordConfig passwordConfig;

    @ApiOperation("用户注册")
    @PostMapping("/save")
    public AjaxResult register(@Validated @RequestBody Register register) {
        //用户注册
        JSONObject resJson = appUserService.register(register);
        //直接登录
        String password = AESUtils.decrypt(register.getPassword(), passwordConfig.getSecretKey().getBytes(StandardCharsets.UTF_8));
        String token = loginService.login(register.getUsername(), password, "", "", Constants.LOGIN_TYPE_APP);
        return success(resJson.put("token", token));
    }

    @ApiOperation("头像上传")
    @PostMapping("/upload")
    public AjaxResult avatarUpload(@RequestPart MultipartFile file) {
        SysUser user = userService.selectUserById(getUserId());
        List<String> pathList = uploadFile(new MultipartFile[]{file}, "user");
        if (StringUtils.isNotEmpty(user.getAvatar())){
            //删除原头像文件
            ComLbsUtils.deleteFile(Collections.singletonList(user.getAvatar()), false);
        }
        user.setAvatar(pathList.get(0));
        userService.updateById(user);
        return success();
    }

}
